// app/utils/token.js
const jwt = require("jsonwebtoken");
const fs = require("fs");
const path = require("path");

const privateKeyPath = path.resolve(__dirname, "../key/private_key.pem");
const publicKeyPath = path.resolve(__dirname, "../key/public_key.pem");

try {
  const privateKey = fs.readFileSync(privateKeyPath, "utf8");
  const publicKey = fs.readFileSync(publicKeyPath, "utf8");

  module.exports = {
    generateToken(payload) {
      return jwt.sign(payload, privateKey, {
        algorithm: "RS256",
        expiresIn: "8h",
      });
    },

    verifyToken(token) {
      try {
        const res = jwt.verify(token, publicKey, { algorithms: ["RS256"] });
        return res;
      } catch (err) {
        throw new Error("无效token");
      }
    },
  };
} catch (err) {
  console.error("没有读取到key:", err);
  throw err;
}
